<template>
  <div class="register-container">
    <div class="register-wrapper">
      <div class="register-card">
        <!-- 头部标题 -->
        <div class="register-header">
          <h1 class="register-title">博客后台注册</h1>
          <p class="register-subtitle">创建您的管理员账户</p>
        </div>

        <!-- 注册表单 -->
        <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="register-form" size="large">
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" clearable />
          </el-form-item>

          <el-form-item prop="email">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱" prefix-icon="Message" clearable />
            <!-- 添加邮箱提示 -->
            <div class="email-tip">
              <span class="tip-text">目前仅支持QQ邮箱</span>
            </div>
          </el-form-item>

          <!-- 验证码输入框 -->
          <el-form-item prop="code">
            <div class="code-input-wrapper">
              <el-input v-model="registerForm.code" placeholder="请输入6位验证码" prefix-icon="Shield" clearable maxlength="6"
                class="code-input" />
              <el-button type="primary" :disabled="!isEmailValid || countdown > 0" :loading="sendingCode"
                @click="sendVerificationCode" class="send-code-btn">
                {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
              show-password clearable />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" prefix-icon="Lock"
              show-password clearable />
          </el-form-item>

          <el-form-item>
            <div class="register-options">
              <el-checkbox v-model="agreeTerms">
                我已阅读并同意
                <el-link type="primary" underline="never">《服务条款》</el-link>
                和
                <el-link type="primary" underline="never">《隐私政策》</el-link>
              </el-checkbox>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="register-button" :loading="loading" :disabled="!agreeTerms"
              @click="handleRegister">
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 底部链接 -->
        <div class="register-footer">
          <span>已有账户？</span>
          <el-link type="primary" underline="never" @click="goToLogin">
            立即登录
          </el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { sendCodeAPI, verifyCodeAPI, adminRegisterAPI } from '@/api/auth/auth'

const router = useRouter()

// 表单引用
const registerFormRef = ref()

// 注册表单数据
const registerForm = reactive({
  username: '',
  email: '',
  code: '',
  password: '',
  confirmPassword: '',
  role: 'user' // 默认角色为用户8
})

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20位', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '用户名只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入有效的邮箱地址',
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      pattern: /^\d{6}$/,
      message: '验证码必须是6位数字',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 其他状态
const loading = ref(false)
const agreeTerms = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer = null

// 计算邮箱是否有效
const isEmailValid = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(registerForm.email)
})

// 发送验证码
const sendVerificationCode = async () => {
  if (!isEmailValid.value) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }

  try {
    sendingCode.value = true
    // 调用后端发送验证码接口
    const { data: res } = await sendCodeAPI(registerForm.email)

    if (res.code !== 200) {
      ElMessage.error(res.data.msg || '验证码发送失败')
      return
    }
    ElMessage.success(res.msg || '验证码已发送，请查收您的邮箱')
    startCountdown()

  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('验证码发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)
}

// 注册处理
const handleRegister = async () => {
  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    if (!agreeTerms.value) {
      ElMessage.warning('请先同意服务条款和隐私政策')
      return
    }

    loading.value = true

    const { data: res } = await verifyCodeAPI(registerForm.code)
    if (res.code !== 200) {
      ElMessage.error(res.msg || '验证码验证失败')
      return
    }
    const submitData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      role: registerForm.role,
      phone: null
    }
    const { data: res2 } = await adminRegisterAPI(submitData)
    if (res2.code !== 200) {
      ElMessage.error(res2.message || '注册失败，请稍后重试')
      return
    }
    ElMessage.success(res2.message || '注册成功，请登录')
    // 注册成功后跳转到登录页面
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.response?.data?.msg || '注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 组件销毁时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-wrapper {
  width: 100%;
  max-width: 450px;
}

.register-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.register-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.register-form {
  margin-bottom: 20px;
}

.register-options {
  width: 100%;
}

.register-options .el-checkbox {
  line-height: 1.5;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
}

.register-footer {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-footer span {
  margin-right: 8px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .register-container {
    padding: 15px;
  }

  .register-wrapper {
    max-width: 400px;
  }

  .register-card {
    padding: 30px 20px;
  }

  .register-title {
    font-size: 24px;
  }

  .register-subtitle {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 10px;
  }

  .register-wrapper {
    max-width: 100%;
  }

  .register-card {
    padding: 25px 15px;
  }

  .register-title {
    font-size: 22px;
  }

  .register-options {
    text-align: left;
  }

  .register-options .el-checkbox {
    font-size: 13px;
  }
}

/* Element Plus 组件样式自定义 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

:deep(.el-button--primary:disabled) {
  background: #c0c4cc;
  transform: none;
  box-shadow: none;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-link) {
  font-size: 14px;
}

/* 验证码输入框样式 */
.code-input-wrapper {
  display: flex;
  gap: 10px;
  align-items: center;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  flex-shrink: 0;
  width: 120px;
  height: 40px;
  font-size: 14px;
}

/* 邮箱提示样式 */
.email-tip {
  padding-left: 2px;
  margin-bottom: -20px;
}

.tip-text {
  font-size: 12px;
  color: #909399;
  line-height: 1;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .tip-text {
    font-size: 11px;
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .code-input-wrapper {
    flex-direction: column;
    gap: 8px;
  }

  .send-code-btn {
    width: 100%;
  }
}
</style>